package com.sqfw.project.system.service.impl;

import com.sqfw.common.enums.UserStatus;
import com.sqfw.common.exception.ServiceException;
import com.sqfw.common.utils.StringUtils;
import com.sqfw.framework.security.LoginUser;
import com.sqfw.framework.security.service.SysPasswordService;
import com.sqfw.framework.security.service.SysPermissionService;
import com.sqfw.project.system.domain.SysConfig;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.system.mapper.SysConfigMapper;
import com.sqfw.project.system.service.ISysUserService;
import com.sqfw.project.system.service.UserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * 用户验证处理
 *
 * @author admin
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;


    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Override
    public UserDetails loadUserByCode(String code) throws UsernameNotFoundException {

        SysUser user = userService.selectUserByCode(code);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户工号：{} 不存在.", code);
//            throw new ServiceException("登录用户工号：" + code + " 不存在");
            throw new ServiceException("用户名或密码错误");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", user.getUserName());
//            throw new ServiceException("对不起，您的账号：" + code + " 已被删除");
            throw new ServiceException("用户名或密码错误");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", user.getUserName());
//            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已停用");
            throw new ServiceException("用户名或密码错误");
        }

        //passwordService.validate(user);

        return createLoginUser(user);
    }

    @Override
    public UserDetails loadUserByUsername(String username)
    {
        SysUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
//            throw new ServiceException("登录用户：" + username + " 不存在");
            throw new ServiceException("用户名或密码错误");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
//            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
            throw new ServiceException("用户名或密码错误");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
//            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
            throw new ServiceException("用户名或密码错误");
        }

//        // 用户信息没有密码最后修改日期，则直接强制修改密码
//        if (user.getPassTime() == null) {
//            log.info("登录用户：{} 密码修改时间的到来.", username);
//            throw new ServiceException("对不起，您的账号：" + username + " 密码需要修改了");
//        } else {
//            // 有最后修改日期则再进行判断
//            // 获取最大密码修改时间间隔（毫秒值）
//            SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("sys.user.pass.interval");
//            Long interval = Long.parseLong(sysConfig.getConfigValue()) * 24 * 60 * 60 * 1000;
//            // 获取用户密码修改间隔
//            Long userInterval = System.currentTimeMillis() - user.getPassTime().getTime();
//            // 如果用户间隔超过间隔上限则要求强制修改密码
//            if (userInterval >= interval) {
//                log.info("登录用户：{} 密码修改时间到了.", username);
//                throw new ServiceException("对不起，您的账号：" + username + " 密码需要修改了");
//            }
//        }
        passwordService.validate(user);

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
